package com.gyx.controller;

import com.gyx.entity.Dept;
import com.gyx.entity.Emp;
import com.gyx.mapper.DeptMapper;
import com.gyx.mapper.EmpMapper;
import com.gyx.utils.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {
    @Autowired
   private EmpMapper empMapper;

    @Autowired
    private DeptMapper deptMapper;

    @RequestMapping("/list")
    public String list(HttpServletRequest request){
        List<Emp> list = empMapper.selectAll();
        request.setAttribute("list",list);
        return "emp/list";
    }

    @RequestMapping("/update")
    public String update(long id,HttpServletRequest request){
        Emp emp = empMapper.selectByPrimaryKey(id);
        request.setAttribute("emp",emp);
        List<Dept> depts=deptMapper.selectAll();
        request.setAttribute("depts",depts);
        return "emp/update";
    }

//    @RequestMapping("/confirmUpdate")
//    public String confirmUpdate(MultipartFile myfile,Emp emp,HttpServletRequest request){
//        /*if (myfile.getSize()!=0){
//            String s=UploadUtils.upload(myfile);
//            emp.setEmpHead(s);
//        }else {
//            emp.setEmpHead(null);
//        }*/
//        int i=empMapper.updateByPrimaryKey(emp);
//        return "redirect:/emp/list";
//    }

//    @RequestMapping("confirmAdd")
//    public String confirmAdd(Emp emp,MultipartFile myfile){
//        String path=UploadUtils.upload(myfile);
//        emp.setEmpHead(path);
//        empMapper.insert(emp);
//        return "redirect:/emp/list";
//    }

    @RequestMapping("/listJson")
    @ResponseBody
    public List<Emp> listJson(){
        List<Emp> emps=empMapper.selectAll();
        return emps;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public int delete(int id){
        int i=empMapper.deleteByPrimaryKey(id);
        return i;
    }

    @RequestMapping("confirmAdd")
    @ResponseBody
    public int confirmAdd(@RequestBody Emp emp){
        System.out.println(emp+"------------");
        int i=empMapper.insert(emp);
        return i;
    }

    @RequestMapping("/confirmUpdate")
    @ResponseBody
    public int confirmUpdate(@RequestBody Emp emp){
        int i=empMapper.updateByPrimaryKeySelective(emp);
        return i;
    }
}
